package com.software.lineragent.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.software.common.CommonUtils;
import com.software.form.billform.dao.BillFormTransaction;
import com.software.form.bookingform.dao.BookingForm;
import com.software.form.bookingform.dao.BookingFormTransaction;
import com.software.form.shippmentinfo.dao.ShippmentInfoTransaction;

public class ShippmentInfoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		BookingFormTransaction bft = (BookingFormTransaction) CommonUtils.getBean("bookingFormTransaction");
		String lagentEmail = (String) request.getSession().getAttribute("user");
		List<BookingForm> confirmeds = bft.getFormByEmail(lagentEmail,1);
		if(confirmeds != null){
			if(confirmeds.size() > 0){
				List list = new ArrayList();
				for(int i = 0; i < confirmeds.size(); i++)
				{
					JSONArray array = new JSONArray();
					array.put(confirmeds.get(i).getNo());
					array.put(confirmeds.get(i).getShipper());
					array.put(confirmeds.get(i).getOv());
					array.put(confirmeds.get(i).getPol());
					array.put(confirmeds.get(i).getSagentEmail());
					list.add(array);
				}
				JSONObject o = new JSONObject();
				try {
					o.put("confirmeds", list);
					CommonUtils.outputJsonData(o.toString(), response);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		BookingFormTransaction bft = (BookingFormTransaction) CommonUtils.getBean("bookingFormTransaction");
		ShippmentInfoTransaction sit = (ShippmentInfoTransaction)CommonUtils.getBean("shippmentInfoTransaction");
		JSONObject json = CommonUtils.readJSONStringFromRequestBody(request, response);
		try{
			String no = json.getString("no");
			String sagentEmail = json.getString("sagentEmail");
			String info = json.getString("info");
			BookingForm bf = bft.getBookingFormByNo(no);
			int id = bf.getId();
			if(bft.updateStatusById(id, 2)){
				if(sit.add(sagentEmail, info, no))
					CommonUtils.outputJsonData(1, response);
			}else{
				CommonUtils.outputJsonData(0, response);
			}
			
		}catch(JSONException je){
			try {
				CommonUtils.outputJsonData(0, response);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
